<?php
namespace Modules\Buy\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Buy\Entities\Brand;
use Modules\Buy\Entities\Brandcate;
use Modules\Buy\Entities\Catego;
use Modules\Buy\Http\Requests\BrandRequest;
class BrandController extends Controller
{
    //显示列表
    public function index()
    {
        $data = Brand::paginate(10);
        return view('buy::brand.index', compact('data'));
    }

    //创建视图
    public function create(Brand $brand,Catego $catego)
    {

//        dd(123);
//        获得所有的顶级分类供品牌页选择
//        $cate = Catego::where('pid',0)->get();
//        dd($cate->toArray());
        $cate = $catego->cateTree();
//        dd($cate);
        return view('buy::brand.create',compact('brand','cate'));
    }

    //保存数据
    public function store(BrandRequest $request,Brand $brand)
    {
//        dd($request->all());
//        dd($brand->toArray());
        $post = $request->all();
        $brand->fill($post);
        $brand->save();
//        先得把品牌表保存了，才能往中间表存数据
        foreach($post['categorys'] as $v){
            Brandcate::create([
                'brand_id'=>$brand['id'],
                'cate_id'=>$v
            ]);
        }
        return redirect('/buy/brand')->with('success', '保存成功');
    }

    //显示记录
    public function show(Brand $field)
    {
        return view('buy::brand.show', compact('field'));
    }

    //编辑视图
    public function edit(Brand $brand,Catego $catego)
    {
//        编辑视图
//        dd($brand->toArray());
//        $cate = Catego::where('pid',0)->get();
//        dd($cate->toArray());
        $cate = $catego->cateTree();
        $zhong = Brandcate::where('brand_id',$brand['id'])->pluck('cate_id');
        $jian = $zhong->toArray();
        return view('buy::brand.edit', compact('brand','cate','jian'));
    }

    //更新数据
    public function update(BrandRequest $request, Brand $brand)
    {
        $post = $request->all();
//        dd($post);
        $brand->update($post);
       Brandcate::where('brand_id',$brand['id'])->delete();
//        dd($res->toArray());
        foreach($post['categorys'] as $v){
            Brandcate::create([
                'brand_id'=>$brand['id'],
                'cate_id'=>$v
            ]);
        }

        return redirect('/buy/brand')->with('success','更新成功');
    }

    //删除模型
    public function destroy(Brand $brand)
    {
        $brand->delete();
        return redirect('buy/brand')->with('success','删除成功');
    }
}
